package com.bookstore.servlet.admin;

import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import com.bookstore.service.impl.UserServiceImpl;
import com.bookstore.servlet.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//管理员模块
@WebServlet("/admin/user.do")
public class UserServlet extends BaseServlet {

    UserService userService = new UserServiceImpl();

    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user.setPassword(password);
        user.setUsername(username);
        User login = userService.login(user);
        response.setContentType("text/html;charset=utf-8");
        if (login != null) {
            //登录成功
            //获取 Session
            HttpSession session = request.getSession();
            session.setAttribute("user", login);
            response.getWriter().print(1);
        } else {
            //登录失败
            response.getWriter().print(0);
        }
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //销毁 Session 对象
        request.getSession().invalidate();
        //重定向回登录页面
        response.sendRedirect("./login.html");
    }
}
